import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:live_music/controller/video_list_controller.dart';
import 'package:live_music/event/videoListEvent.dart';
import 'package:live_music/models/moment_detail_model.dart';
import 'package:live_music/models/moment_list_model.dart';
import 'package:live_music/pages/video/index.dart';
import 'package:live_music/services/momentService.dart';
import 'package:live_music/services/squareService.dart';
import 'package:live_music/utils/eventBusUtils.dart';

///视频列表页
class VideoListPage extends StatefulWidget {
  VideoListPage({Key key, this.momentId}) : super(key: key);
  int momentId;
  @override
  _VideoListPageState createState() {
    return _VideoListPageState();
  }
}

class _VideoListPageState extends State<VideoListPage>
    with AutomaticKeepAliveClientMixin {
  PageController _pageController = PageController(keepPage: true);
  VideoListController _videoListController = Get.put(VideoListController());
  int pageNo = 1;
  int pageSize = 15;
  bool hasMore = true;
  List<MomentDetailModel> _momentListModel = [];
  MomentDetailModel curMomentDetail;
  @override
  void initState() {
    super.initState();
    initData();
  }

  initData() async {
    await loadCurData();
    await loadCurAboutIdData();

    EventBusUtils.getInstance().on<CurVideoListIndexEvent>().listen((event) {
      if (_momentListModel.length < event.index + 3) {
        if (hasMore) {
          loadCurAboutIdData(replace: false);
        }
      }
    });
  }

  loadCurData() async {
    Map<String, dynamic> data = {"momentId": widget.momentId};
    Map<String, dynamic> detailData =
        await MomentService.queryMomentDetail(data);
    MomentDetailModel momentDetail =
        MomentDetailModel.fromJson(detailData['body']);
    _videoListController.curentVideo(momentDetail);
    curMomentDetail = momentDetail;
  }

  loadCurAboutIdData({bool replace = true}) async {
    Map<String, dynamic> data = {
      "pageNo": pageNo,
      "pageSize": pageSize,
      "repostMomentId": 0,
      "momentType": "VIDEO"
    };
    Map<String, dynamic> result = await SquareService.querySquareMoment(data);
    List<dynamic> momentList = result['body'];
    MomentListModel momentListModel = MomentListModel.fromJson(momentList);
    setState(() {
      pageNo++;
      hasMore = pageSize == momentListModel.list.length;
      if (replace) {
        _momentListModel = [curMomentDetail];
        for (var item in momentListModel.list) {
          if (item.id != curMomentDetail.id) {
            _momentListModel.add(item);
          }
        }
      } else {
       for (var item in momentListModel.list) {
          if (item.id != curMomentDetail.id) {
            _momentListModel.add(item);
          }
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ));
    return Scaffold(
      backgroundColor: Colors.black,
      body: Container(
        height: MediaQuery.of(context).size.height,
        child: Stack(
          children: [
            _getVideoPageView(),
            // _getTopBarLayout(),
          ],
        ),
      ),
    );
  }

  _getTopBarLayout() {
    return Container(
      height: 40,
      constraints: BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width,
          maxHeight: 40,
          minHeight: 40),
      margin:
          EdgeInsets.only(top: MediaQueryData.fromWindow(window).padding.top),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
            left: 0,
            child: IconButton(
              icon: Icon(
                Icons.arrow_back_ios_rounded,
                color: Colors.white,
              ),
              onPressed: () {
                Get.back();
              },
            ),
          ),
          Positioned(
              right: 0,
              child: IconButton(
                icon: Icon(
                  Icons.search_rounded,
                  color: Colors.white,
                ),
              ))
        ],
      ),
    );
  }

  _getVideoPageView() {
    double contentHeight = MediaQuery.of(context).size.height -
        48 -
        MediaQueryData.fromWindow(window).padding.top;
    return Container(
        constraints: BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width,
          maxHeight: contentHeight,
        ),
        margin:
            EdgeInsets.only(top: MediaQueryData.fromWindow(window).padding.top),
        child: PageView.builder(
          controller: _pageController,
          itemCount: _momentListModel.length,
          scrollDirection: Axis.vertical,
          itemBuilder: (context, index) {
            return VideoWidget(
                index: index, videoItem: _momentListModel[index]);
          },
        ));
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
